package cn.dida.core;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.env.Environment;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

import cn.dida.model.Sysres;
/**
 * 全局拦截器
 * @author weiwei
 *
 */
public class GlobalInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
/*
        // 请求对象放入线程变量容器
        ThreadLocalContainer.setRequest(request);
        // 生成唯一标识符
        ThreadLocalContainer.setSubjectId(UUID.randomUUID().toString());
*/


        String requestURI = request.getRequestURI();
        UriComponents uriComponents = UriComponentsBuilder.fromUriString(requestURI).build();

        List<String> Path_Segments = uriComponents.getPathSegments();
        Sysres Current_Res_Node = SysresMap.getNavNodeByPath(requestURI, request.getMethod());
        List<Sysres> Res_Node_Link = SysresMap.getNavNodeLinkByPath(requestURI, request.getMethod());
        request.setAttribute("Path_Segments", Path_Segments);
        request.setAttribute("Current_Res_Node", Current_Res_Node);
        request.setAttribute("Res_Node_Link", Res_Node_Link);

/*
        // Current_Res_Node放入线程变量容器
        ThreadLocalContainer.setCurrentResNode(Current_Res_Node);*/
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        Environment env = SpringApplicationContext.getEnvironment();

        List<String> Path_Segments = (List<String>) request.getAttribute("Path_Segments");
        Sysres Current_Res_Node = (Sysres) request.getAttribute("Current_Res_Node");
        List<Sysres> Res_Node_Link = (List<Sysres>) request.getAttribute("Res_Node_Link");

        if (modelAndView != null) {
            Map<String, Object> model = modelAndView.getModel();
            model.put("PicDomain", env.getProperty("pic.domain"));
            model.put("Current_Res_Node", Current_Res_Node);
            model.put("Res_Node_Link", Res_Node_Link);
        }
    }

}